import {requestPhoneCode,login} from "@/api/login"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone: '',
    checked: false,  // 复选框是否选中的状态
    remainSeconds: 60, // 剩余秒数
    verifyCode: '',
    codeBtnDisabled: false,
    sendMsg: '获取验证码',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  checkboxChange: function (e) {
    console.log(e.detail.value)
    if(e.detail.value.length >0){
    this.setData({
      checked: true  // 更新复选框的状态
    });
  }else{
    this.setData({
      checked: false  // 更新复选框的状态
    });
  }
  },

  //发送验证码
  codeBtnAction: function () {
    if (this.data.codeBtnDisabled) {
      return;
    }
    if (this.data.phone.length == 0) {
      wx.toast({title:'请输入手机号'});
      return;
    }
    this.requestPhoneCode();
  },

  // 提交信息
  doneBtnAction: function () {
    if (this.data.phone.length == 0) {
      wx.toast({title:'请输入手机号'});
      return;
    }
    if (this.data.verifyCode.length == 0) {
      wx.toast({title:'请输入验证码'});
      return;
    }
    if (!this.data.checked) {
      wx.toast({title:'请勾选用户隐私协议'});
      return;
    }
    this.requestEditPwd();
  },

  /**** Request */

  //验证码
  async requestPhoneCode() {
    // 禁用按钮
    this.setData({
      codeBtnDisabled: true
    });
     // 开始倒计时
     this.startCountDown();
    const res = await requestPhoneCode(this.data.phone)
    const {code} = res
    if(code === 0){
      wx.toast({title:'发送验证码成功'});
    }
  },

 // 开始倒计时
 startCountDown: function() {
  var that = this;
  var remainSeconds = that.data.remainSeconds;

  // 设置定时器，每秒更新剩余秒数
  var timer = setInterval(function() {
    remainSeconds--;
    if (remainSeconds <= 0) {
      // 倒计时结束，清除定时器，恢复按钮状态
      clearInterval(timer);
      that.setData({
        codeBtnDisabled: false,
        sendMsg: '获取验证码',
        remainSeconds: 60 // 重置为60秒
      });
    } else {
      that.setData({
        sendMsg: remainSeconds + '秒'
      });
    }
  }, 1000);

  // 初始设置一次sendMsg
  that.setData({
    sendMsg: remainSeconds + '秒'
  });
},

  //登录
  async requestEditPwd(){
    var that = this;
    const parm = {
      phone: this.data.phone.toString(),
      code:this.data.verifyCode
    }
    const res = await login(parm)
    if(res.code === 0){
      //登录成功保存token,保存用户信息
      app.globalData.userInfo = res.data;
      wx.setStorage({
        key: "phoneInfo",
        data: res.data
    })
      setTimeout(()=>{
        this.toLoginPage()
      },1000) //延迟时间 这里是1秒
    }
  },
  toLoginPage: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
})